package com.qijian.web.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qijian.common.annotation.Log;
import com.qijian.common.annotation.PlugAnn;
import com.qijian.common.annotation.PlugParam;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.domain.entity.FlowableApproval;
import com.qijian.common.core.domain.entity.FlowableBack;
import com.qijian.common.core.page.TableDataInfo;
import com.qijian.common.enums.ApprovalDescriptionEnum;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.utils.DateUtils;
import com.qijian.common.utils.ObjectUtils;
import com.qijian.common.utils.SecurityUtils;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.maindata.domain.BomMaterialPre;
import com.qijian.maindata.domain.BomMaterialPreDetail;
import com.qijian.maindata.domain.query.BomMaterialPreDetailQuery;
import com.qijian.maindata.domain.query.BomMaterialPreQuery;
import com.qijian.maindata.service.IBomMaterialPreDetailService;
import com.qijian.maindata.service.IBomMaterialPreService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * 生产BOM用料预算单据Controller
 *
 * @author qijian
 * @date 2022-05-17
 */
@Api(tags = "工艺管理：生产BOM用料预算单据")
@RestController
@RequiredArgsConstructor
@RequestMapping("/maindata/materialPre")
public class BomMaterialPreController extends BaseController {

    private final IBomMaterialPreService bomMaterialPreService;
    private final IBomMaterialPreDetailService bomMaterialPreDetailService;

    /**
     * 查询生产BOM用料预算单据列表
     */
    @PreAuthorize("@ss.hasPermi('maindata:materialPre:list')")
    @GetMapping("/list")
    public TableDataInfo list(BomMaterialPreQuery query, IPage<BomMaterialPre> page) {
        return getDataTable(bomMaterialPreService.page(Page.of(page.getCurrent(), page.getSize()), WhereEntityTool.invoke(query)));
    }

    @PreAuthorize("@ss.hasPermi('maindata:materialPre:list')")
    @GetMapping("/detail/list")
    public TableDataInfo detailList(BomMaterialPreDetailQuery query, IPage<BomMaterialPreDetail> page) {
        return getDataTable(bomMaterialPreDetailService.page(Page.of(page.getCurrent(), page.getSize()), WhereEntityTool.invoke(query)));
    }


    @GetMapping("/cost")
    public TableDataInfo detailList(BomMaterialPreDetailQuery query) {
        return getDataTable(bomMaterialPreDetailService.selectCostByProject(WhereEntityTool.invoke(query)));
    }


    /**
     * 导出生产BOM用料预算单据列表
     */
    @PreAuthorize("@ss.hasPermi('maindata:materialPre:export')")
    @Log(title = "生产BOM用料预算单据", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(BomMaterialPreQuery query, HttpServletResponse response) {
        new ExcelUtil<>(BomMaterialPre.class).exportExcel(response, bomMaterialPreService.list(WhereEntityTool.invoke(query)), "生产BOM用料预算单据数据");
    }


    /**
     * 导出生产BOM用料预算单据列表
     */
    @PreAuthorize("@ss.hasPermi('maindata:materialPre:export')")
    @Log(title = "生产BOM用料预算单据", businessType = BusinessType.EXPORT)
    @GetMapping("/exportDetail")
    public void export(BomMaterialPreDetailQuery query, HttpServletResponse response) {
        new ExcelUtil<>(BomMaterialPreDetail.class).exportExcel(response, bomMaterialPreDetailService.list(WhereEntityTool.invoke(query)), "生产BOM用料预算单据数据");
    }

    @PreAuthorize("@ss.hasPermi('maindata:materialPre:import')")
    @Log(title = "材料预算导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importMaterial(MultipartFile file, boolean updateSupport) throws Exception {
        List<BomMaterialPreDetail> list = new ExcelUtil<>(BomMaterialPreDetail.class).importExcel(file.getInputStream());
//        bomMaterialPreDetailService.importBase(list);
        List<BomMaterialPreDetail> resultUpdate = new ArrayList<>();
        list.forEach(x -> {
            if (ObjectUtils.isNull(x.getItemPrices())) {
                throw new ServiceException("E01:缺少物料预算单价！");
            }
            BomMaterialPreDetail detail = bomMaterialPreDetailService.getById(x.getId());
            if (ObjectUtils.isNull(detail)) {
                throw new ServiceException("E01:物料信息为空");
            }
            detail.setItemPrices(x.getItemPrices());
            resultUpdate.add(detail);
        });
        if (resultUpdate.size() > 0) {
            bomMaterialPreDetailService.updateBatchById(resultUpdate);
        }
        return AjaxResult.success();
    }

    /**
     * 获取生产BOM用料预算单据详细信息
     */
    @PreAuthorize("@ss.hasPermi('maindata:materialPre:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        BomMaterialPre bomMaterialPre = bomMaterialPreService.selectVoById(id);
        return AjaxResult.success(bomMaterialPre);
    }

    /**
     * 修改生产BOM用料预算单据
     */
    @PreAuthorize("@ss.hasPermi('maindata:materialPre:edit')")
    @Log(title = "生产BOM用料预算单据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BomMaterialPre bomMaterialPre) {
        BomMaterialPre info = bomMaterialPreService.getById(bomMaterialPre.getId());
        if (ApprovalDescriptionEnum.A != info.getApprovalStatus() && ApprovalDescriptionEnum.D != info.getApprovalStatus()) {
            throw new ServiceException("E01:单据审核中或已审核，无法删除！");
        }
        bomMaterialPre.setIssueId(SecurityUtils.getUserId());
        bomMaterialPre.setIssueNickName(SecurityUtils.getNickName());
        bomMaterialPre.setWorkTime(DateUtils.getNowDate());
        return toAjax(bomMaterialPreService.saveOrUpdateVo(bomMaterialPre, false));
    }

    /**
     * 删除生产BOM用料预算单据
     */
    @PreAuthorize("@ss.hasPermi('maindata:materialPre:remove')")
    @Log(title = "生产BOM用料预算单据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        BomMaterialPreQuery query = new BomMaterialPreQuery();
        query.setIds(new HashSet<>(ids));
        query.setApprovalStatusNot(ApprovalDescriptionEnum.A);
        if (bomMaterialPreService.count(WhereEntityTool.invoke(query)) > 0) {
            throw new ServiceException("E01:单据审核中或已审核，无法删除！");
        }
        return toAjax(bomMaterialPreService.removeByIds(ids));
    }

    /**
     * 单据提交审核
     */
    @Log(title = "生产BOM用料预算单据", businessType = BusinessType.APPROVAL)
    @PlugAnn(groupClass = FlowableApproval.Approval.class, params = {"'bomMaterialPre'", "T(com.qijian.common.utils.SecurityUtils).getUserId()", "T(com.qijian.common.utils.SecurityUtils).getDeptId()", "T(com.qijian.common.utils.SecurityUtils).getNickName()"})
    @GetMapping(value = "/approval/{id}")
    public AjaxResult approval(@PlugParam @PathVariable("id") Long id) {
        BomMaterialPre info = bomMaterialPreService.getById(id);
        if (ObjectUtils.isNull(info)) {
            throw new ServiceException("E01:单据信息错误！");
        } else if (info.getApprovalStatus() == ApprovalDescriptionEnum.B) {
            throw new ServiceException("E01:单据审核中！");
        } else if (info.getApprovalStatus() == ApprovalDescriptionEnum.C) {
            throw new ServiceException("E01:单据已审核！");
        }
        BomMaterialPre bomMaterialPreChange = new BomMaterialPre();
        bomMaterialPreChange.setId(id);
        bomMaterialPreChange.setApprovalStatus(ApprovalDescriptionEnum.B);
        bomMaterialPreChange.setStatus(2);
        return AjaxResult.success(bomMaterialPreService.updateById(bomMaterialPreChange));
    }


    /**
     * 单据反审核
     */
    @Log(title = "生产BOM用料预算单据", businessType = BusinessType.APPROVAL)
    @PreAuthorize("@ss.hasPermi('maindata:materialPre:deApproval')")
    @PlugAnn(groupClass = FlowableBack.Approval.class, params = {"'bomMaterialPre'"})
    @GetMapping(value = "/deApproval/{id}")
    public AjaxResult deApproval(@PlugParam @PathVariable("id") Long id) {
        BomMaterialPre bomMaterialPreChange = new BomMaterialPre();
        bomMaterialPreChange.setId(id);
        bomMaterialPreChange.setApprovalStatus(ApprovalDescriptionEnum.D);
        return AjaxResult.success(bomMaterialPreService.updateById(bomMaterialPreChange));
    }
}
